package cn.tedu._05weibo.exception;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理器:处理所有的由控制器Controller抛出的异常
 * Exception注解:标识此方法为异常处理方法；
 *ResponseBody
 */
@Slf4j
//@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        String message = ex.getMessage();
        log.error("IllegalArgumentException:" +message );

        return new JsonResult(StatusCode.OPERATION_FAILED,message);
    }

//   @ExceptionHandler
//    public  JsonResult doHandleRuntimeException(RuntimeException ex){
//        String message = ex.getMessage();
//        log.error("RuntimeException: " + message);
//        return new JsonResult(StatusCode.OPERATION_FAILED,message);
//   }

   @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        //验证POJO类型参数时，获取提示消息：ex.getFieldError().getDefaultMessage();
       String message= ex.getFieldError().getDefaultMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
   }


   @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException ex){
        String message =ex.getMessage().split(":")[1].trim();
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
   }
    /**
     * 能处理控制器抛出的所有异常
     */

//   @ExceptionHandler
//    public JsonResult doHandleThrowableException(Throwable ex){
//        String message = ex.getMessage();
//        log.error("Throwable:" +message);
//        return new JsonResult(StatusCode.THROWABLE_ERROR,message);
//   }
}
